import axios from "axios";
import app from '../main'
import { ElLoading,ElMessageBox,ElMessage } from "element-plus";


function getTokenByLoacal(){
    return JSON.parse(sessionStorage.getItem('ms_token'))
}
let loadingObj = null;

const service = axios.create({
    baseURL:'http://47.113.217.179:8080/',
    timeout:5000,
    headers:{
        "Content-type":"application/json;charset=utf-8"
    }
})

let loading = false;

//请求拦截
service.interceptors.request.use(
    config => {
        loading = sessionStorage.getItem('ms_username')==null?true:false;
        if(loading){
            loadingObj = ElLoading.service({
                lock:true,
                text:'Loading',
                background:'rgb(0,0,0,0.7)',
            })
        }
        if(getTokenByLoacal()){
            //如何让每一个接口带token
            config.headers['token'] = getTokenByLoacal(0);
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)

//响应拦截
service.interceptors.response.use( 
    response => {
        if(loading && loadingObj){
            loadingObj.close()
        }
        let res = response.data
        //data.data是token
        let accessToken = res.data;
        if(accessToken && accessToken !== '' && !sessionStorage.getItem("token")){
            sessionStorage.setItem('ms_token',JSON.stringify(accessToken))
        }
        if(res.code === 401){
            console.log("res.msg:",res.msg)
            ElMessageBox.alert('需要您重新登录在进行操作', '提示', {
                confirmButtonText: 'OK',
                callback: (action) => {
                  ElMessage({
                    type: 'info',
                    message: '请退出后重新登录',
                  })
                },
            })
            return;
        }
        return Promise.resolve(res)
    },
    error => {
        if(loading && loadingObj){
            loadingObj.close()
        }
        return Promise.reject(error);
    }
)

export const post=config=>{
    return service({
        ...config,
        method:'post',
        data:config.data
    })
}

export const get=config=>{
    return service({
        ...config,
        method:'get',
        data:config.data
    })
}

export const put=config=>{
    return service({
        ...config,
        method:'put',
        data:config.data
    })
}

export default service;